<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/1/18
 * Time: 21:58
 */

namespace app\admin\controller;


use app\admin\logic\NoteLogic;
use app\common\controller\Backend;
use app\common\utils\WeChatUtils;
use think\Config;
use think\Db;
use think\Exception;

/**
 * 签管理
 *
 * @icon fa fa-users
 * @remark
 */
class Note extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Note');
        $solve_note_list = model('SolveNote')->select();
        $solve_note_name_list =[];
        foreach ($solve_note_list as $key=>$value){
            $solve_note_name_list[$value['id']]=$value['name'];
        }
        $this->view->assign('solve_note_list',$solve_note_name_list);
        $type_list = model('Type')->select();
        $type_name_list = [];
        foreach ($type_list as $key=>$value){
            $type_name_list[$value['id']]=$value['name'];
        }
        $this->view->assign('type_list',$type_name_list);
    }

    /**
     * 查看
     * @param $ids string 寺庙id
     * @return string
     */
    public function index($ids='')
    {
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if(!empty($ids)) {
                $map = array('temple_id' => $ids);
            }else{
                $map = [];
            }
            $map['is_delete'] = 0;
            $total = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key=>&$value){
                $solve_note_ids = $value['solve_note_ids'];
                $solve_note_list = model('SolveNote')
                    ->where('id','in',$solve_note_ids)
                    ->select();
                $solve_note_name_list =[];
                foreach ($solve_note_list as $k=>$v){
                    $solve_note_name_list[]=$v['content'];
                }
                $content_list = model('Content')
                    ->where(array('note_id'=>$value['id']))
                    ->select();
                $content_array = [];
                foreach ($content_list as $k=>$content){
                    $content_array[]=$content['content'];
                }
                $value['solve_note_text'] = implode(',', $solve_note_name_list);
                $value['content_text'] = implode(',', $content_array);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig('temple_id',$ids);
        $this->view->assign('temple_id',$ids);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add($temple_id='')
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                $type_ids = $this->request->post("solve_note_type/a");
                $content_list = $this->request->post("content/a");
                $solve_content_list = $this->request->post("solve_content/a");
                $logic = new NoteLogic();
                $result = $logic->addNote($params,$type_ids,$content_list,$solve_content_list);
                if ($result['status'] == 1) {
                    $this->success('添加成功!');
                } else if($result['status'] == 2){
                    $this->error($result['msg']);
                }else{
                    $this->error('添加失败!','',$result['error']);
                }
            }
            $this->error('添加失败!');
        }
        $this->assignconfig('temple_id',$temple_id);
        $this->view->assign('temple_id',$temple_id);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params) {
                $type_ids = $this->request->post("solve_note_type/a");
                $content_list = $this->request->post("content/a");
                $solve_content_list = $this->request->post("solve_content/a");
                $logic = new NoteLogic();
                $params['id'] = $ids;
                $result = $logic->editNote($params,$type_ids,$content_list,$solve_content_list);
                if ($result['status'] == 1) {
                    $this->success('修改成功!');
                } else if($result['status'] == 2){
                    $this->error($result['msg']);
                }else{
                    $this->error('修改失败!');
                }
            }
            $this->error('修改失败!');
        }
        $row['solve_note_ids'] = explode(',',$row['solve_note_ids']);
        $this->view->assign("row", $row);
        $this->assignconfig("note_id", $ids);
        return $this->view->fetch();
    }

    /**
     * ajax获取签内容列表
     */
    public function getContentList(){
        $note_id = $this->request->post('note_id');
        $content_list = model('Content')
            ->where(array('note_id'=>$note_id))
            ->select();
        return json($content_list);
    }

    /**
     * ajax获取解签列表
     * @return \think\response\Json
     */
    public function getSolveNoteList(){
        $note_id = $this->request->post('note_id');
        $solve_note_ids = model('Note')
            ->where(array('id'=>$note_id))
            ->value('solve_note_ids');
        $solve_note_ids_arr = explode(',',$solve_note_ids);
        $solve_note_list = model('SolveNote')->where('id','in',$solve_note_ids_arr)->select();
        return json($solve_note_list);
    }

    /**
     * ajax获取解签类型列表
     * @return \think\response\Json
     */
    public function solve_note_type_list(){
        $type_list = model('Type')->select();
        return json($type_list);
    }

    /**
     * 获取二维码
     * @param string $ids
     * @return string
     */
    public function qr_code($ids=''){
        $host = 'http://'.$_SERVER['HTTP_HOST'];
        $this->assignconfig('host',$host);
        $this->assignconfig('note_id',$ids);
        $this->view->assign('note_id',$ids);
        return $this->view->fetch();
    }

    public function qr_code_url($note_id){
        $we_chat = Config::get('WeChat');
        $utils = new WeChatUtils($we_chat['app_id'], $we_chat['app_secret'], $we_chat['token']);
        $this->view->engine->layout(false);
        $utils->getQRCode($note_id);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            Db::startTrans();
            try {
                $result = $this->model->where(array('id'=>$ids))->setField('is_delete',1);
                if($result){
                    Db::commit();
                    $this->success('删除成功!');
                }else {
                    $this->error('删除失败!');
                }
            }catch (Exception $e){
                Db::rollback();
                $this->error('删除失败!');
            }

        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }
}